package de.mmis.helferlein.demo;

import java.io.IOException;
import java.net.UnknownHostException;

import de.mmis.core.base.infrastructure.Infrastructure;
import de.mmis.core.base.infrastructure.InfrastructureException;
import de.mmis.core.base.infrastructure.PublishedDeviceDescription;
import de.mmis.core.base.infrastructure.PublishedDeviceDescription.PublishType;
import de.mmis.core.infrastructure.DistributedInfrastructure;
import de.mmis.core.pojop.NetworkProxy;

public class SearchForMultiplier {

	private static <T> T getNetworkProxy(Infrastructure infrastructure,
			String id, Class<T> clazz) throws InfrastructureException,
			UnknownHostException, IOException {
		// create search pattern
		PublishedDeviceDescription pattern = new PublishedDeviceDescription(id,
				null, PublishType.SOCKET, null, -1);

		// discover the device
		PublishedDeviceDescription device = infrastructure.searchSingleDevice(
				pattern, 1000);

		String host = device.getHost().getHostAddress();
		int port = device.getPort();
		return NetworkProxy.createProxy(clazz, host, port);
	}

	public static void main(String[] args) throws UnknownHostException,
			InfrastructureException, IOException {
		// create infrastructure
		Infrastructure infrastructure = DistributedInfrastructure
				.createInstance(null);
		// search for a multiplier witht the given ID
		Multiplier m = getNetworkProxy(infrastructure, "M3", Multiplier.class);

		// use it
		System.out.println("Result: " + m.multiply(5));

		System.in.read();
	}
}
